package group

import (
	"api/common"
	"api/pb/group"
	"context"
	"errors"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateGroupLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateGroupLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateGroupLogic {
	return &CreateGroupLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// CreateGroup 创建群聊
func (l *CreateGroupLogic) CreateGroup(req *types.GroupInfo) (resp *types.Empty, err error) {
	// 1. 校验参数
	if req.Name == "" {
		return nil, errors.New("group name is empty")
	}

	// 2. 获取群主标识
	userID, err := common.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}

	// 3. 创建群
	_, err = l.svcCtx.GroupRPC.CreateGroup(l.ctx, &group.GroupInfo{
		UserId:   userID,
		Name:     req.Name,
		Desc:     req.Desc,
		Avatar:   req.Avatar,
		Status:   req.Status,
		JoinType: req.JoinType,
	})
	if err != nil {
		return nil, err
	}

	// 4. 返回结果
	return &types.Empty{}, nil
}
